package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    BrandService brandService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    AttrService attrService;


    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;


    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    WareFeignService wareFeignService;


    @Autowired
    SearchFeignService searchFeignService;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {


        //1、保存spu基本信息、 pms_spu_info

        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();

        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveSpuBaseInfo(spuInfoEntity);


        //2、保存spu的描述图片pms_spu_info_desc

        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decript));

        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);


        //4、保存spu的规格参数; pms_product_attr_value

        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(byId.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());

        attrValueService.saveProductAttr(collect);


        //5、保存spu的积分信息; gulimall_sms->sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBouds(spuBoundTo);

        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }


        //5、保存当前spu对应的所有sku信息;
        List<Skus> skus = spuSaveVo.getSkus();
        for (Skus sk : skus) {

            String defaultImg = "";

            for (Images image : sk.getImages()) {
                if (image.getDefaultImg() == 1) {
                    defaultImg = image.getImgUrl();
                }
            }
            //5.1)、sku的基本信息.;pms_sku_info
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sk, skuInfoEntity);
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setSkuDefaultImg(defaultImg);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoService.saveSkuInfo(skuInfoEntity);

            Long skuId = skuInfoEntity.getSkuId();
            List<SkuImagesEntity> collect1 = sk.getImages().stream().map((img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();

                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgUrl(img.getImgUrl());
                skuImagesEntity.setDefaultImg(img.getDefaultImg());

                return skuImagesEntity;
            })).filter((entity -> {
                return !StringUtils.isEmpty(entity.getImgUrl());
            })).collect(Collectors.toList());

            //5.2)、sku的图片信息.;pms_sku_images
            skuImagesService.saveBatch(collect1);


            //5.3)、sku的销售属性信息:pms_sku_sale_attr_value

            List<Attr> attr = sk.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());

            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);


            //5.4)、sku的优惠、满减等信息;gulimalL_sms->sms_sku_Ladde...


            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(sk, skuReductionTo);
            skuReductionTo.setSkuId(skuId);
            log.debug(skuReductionTo.toString());
            if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                R r1 = couponFeignService.saveReduction(skuReductionTo);

                if (r1.getCode() != 0) {
                    log.error("远程保存spu优惠信息失败");
                }
            }
        }


    }

    @Override
    public void saveSpuBaseInfo(SpuInfoEntity spuInfoEntity) {

        this.baseMapper.insert(spuInfoEntity);
    }

    /*

    {
   page: 1,//当前页码
   limit: 10,//每页记录数
   sidx: 'id',//排序字段
   order: 'asc/desc',//排序方式
   key: '华为',//检索关键字
   catelogId: 6,//三级分类id
   brandId: 1,//品牌id
   status: 0,//商品状态
}
     */

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            }));
        }


        String catelogId = (String) params.get("catelogId");

        if (!StringUtils.isEmpty(catelogId) && !catelogId.equals("0")) {
            queryWrapper.and((wrapper -> {
                wrapper.eq("catalog_id", catelogId);
            }));

        }


        String brandId = (String) params.get("brandId");

        if (!StringUtils.isEmpty(brandId) && !brandId.equals("0")) {
            queryWrapper.and((wrapper -> {
                wrapper.eq("brand_id", brandId);
            }));
        }

        String status = (String) params.get("status");

        if (!StringUtils.isEmpty(status) && !status.equals("0")) {
            queryWrapper.and((wrapper -> {
                wrapper.eq("publish_status", status);
            }));
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {


        List<SkuEsModel> list = new ArrayList<>();


        List<SkuInfoEntity> skusBySpuId = skuInfoService.getSkusBySpuId(spuId);


        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseListForSpu(spuId);

        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        Set<Long> setIds = new HashSet<>(searchAttrIds);

        //查询可被检索的参数
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return setIds.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());


        // TODO 查询是否有库存

        Map<Long, Boolean> skuHasStockMap = new HashMap<>();
        List<Long> skuIds = skusBySpuId.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        try {
//            Object o = wareFeignService.getSkuMapping(skuIds).get("data");
//            System.out.println(o);
//            List<SkuHasStockVo> skuHasStockVoList = (List<SkuHasStockVo>) o;
            R r=wareFeignService.getSkuMapping(skuIds);

//            System.out.println(skuHasStockVoList.toString());
//            skuHasStockMap = skuHasStockVoList.getData().stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()==null?false:item.getHasStock()));
//            skuHasStockMap=new HashMap<>();
//            for (int i=0;i<skuHasStockVoList.size();i++){
//                SkuHasStockVo skuHasStockVo = skuHasStockVoList.get(i);
//                skuHasStockMap.put(skuHasStockVo.getSkuId(),skuHasStockVo.getHasStock());
//            }
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            List<SkuHasStockVo> data = r.getData(typeReference);
            for(SkuHasStockVo vo:data){
                Long key=vo.getSkuId();
                Boolean hasStock = vo.getHasStock();
                skuHasStockMap.put(key,hasStock);
            }
//            skuHasStockMap = r.getData(typeReference).stream().collect(Collectors.toMap((item->{
//              return item.getSkuId();
//            }), (item -> {
//                return item.getHasStock();
//            })));
        } catch (Exception e) {
            log.error("库存服务查询异常：{}", e);
        }


        Map<Long, Boolean> stockMap = skuHasStockMap;

        // TODO 查询出sku可以用来被检索的规格属性

        //封装每个sku的信息
        List<SkuEsModel> upProducts = skusBySpuId.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);

            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            if (stockMap!=null){
                esModel.setHasStock(stockMap.get(sku.getSkuId()));
            }else {
                esModel.setHasStock(false);
            }


            // TODO 热度评分


            esModel.setHotScore(0L);

            // TODO 查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(esModel.getBrandId());

            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());

            //设置检索属性
            esModel.setAttrs(attrsList);


            return esModel;

        }).collect(Collectors.toList());


        //TODO 将数据发送给es进行保存

        R r = searchFeignService.productStatusUp(upProducts);

        if (r.getCode()==0){
            //远程调用成功
            baseMapper.updataSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());

        }else {
            //远程调用失败


        }


    }


}